/**
 * 
 */
package com.hfqixin.manager.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hfqixin.core.util.Util;

/** 
 *  Title: com.hzdracom.manager.controller
 *  Description: 
 *  Company: 杭州龙骞科技有限公司 
 *  @author  panke
 *  @date 2017年3月17日 
 */
@Controller
@RequestMapping("upload")
public class FileUploadController extends  BaseController{

	private  Logger logger = Logger.getLogger(getClass());
	
	@RequestMapping("image")
	public void imageUpload(HttpServletResponse response,HttpServletRequest request){
		MultipartFile file = null;
		System.err.println("图片上传");
		if (request instanceof MultipartHttpServletRequest) {
			Collection<MultipartFile> files = ((MultipartHttpServletRequest) request).getFileMap().values();
			if (files != null && !files.isEmpty()) {
				file = new ArrayList<MultipartFile>(files).get(0);
			} else {
				respErrorMsg(response, "请至少选择一个文件");
				return;
			}
		} else {
			respErrorMsg(response, "请至少选择一个文件");
			return;
		}

		try {
			if (file.isEmpty()) {
				respErrorMsg(response, "请至少选择一个文件");
				return;
			} else {

				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
			    String res = sdf.format(new Date());
				
				 // uploads文件夹位置
		        String rootPath = request.getSession().getServletContext().getRealPath("uploads/");
		        //原始名称
				String originalFileName = file.getOriginalFilename();
				
				 // 新文件名
		        String newFileName = "hfqixin" + res + originalFileName.substring(originalFileName.lastIndexOf("."));
			/*	String fileExtName = tempFileName.substring(tempFileName.lastIndexOf(".") + 1).toLowerCase();  //获取文件后缀
*/				 // 创建年月文件夹
		        Calendar date = Calendar.getInstance();
		        File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1));
				Iterator iter = multiRequest.getFileNames();
				System.err.println(rootPath);
				while (iter.hasNext()) {
					// 一次遍历所有文件
					file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						System.err.println("11");
						 // 新文件
				        File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
				        // 判断目标文件所在目录是否存在
				        if( !newFile.getParentFile().exists()) {
				            // 如果目标文件所在的目录不存在，则创建父目录
				            newFile.getParentFile().mkdirs();
				        }
				        System.out.println(newFile);
				        // 将内存中的数据写入磁盘
				        file.transferTo(newFile);
				        String requestUrl = request.getScheme() //当前链接使用的协议
				        	    +"://" + request.getServerName()//服务器地址 
				        	    + ":" + request.getServerPort() //端口号 
				        	    + request.getContextPath(); //应用名称，如果应用名称为
				        // 完整的url
				        String path =requestUrl+"/uploads/"+date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH)+1) + "/" + newFileName;
				        System.err.println(path);
				  
				        	  
				        	   
				        System.err.println(requestUrl);
				        respSuccessMsg(response, path, "上传成功");
					}

				}
				
			}
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			respErrorMsg(response, "请至少选择一个文件");
			return;
		}
	}
	
	/**
	 *  空接口
	 */
	@RequestMapping("void")
	public void voidInterface(HttpServletResponse response){
		respSuccessMsg(response, "", "");
	}
	
	
}
